# amazon web service
#

require 'openssl'
require 'base64'
require 'cgi'

require 'aws_pass'

def aws_signed_url(req)
  message = ["GET", AWS_URL, AWS_PATH, req].join("\n")
  hash = OpenSSL::HMAC::digest(OpenSSL::Digest::SHA256.new, AWS_SECRET_KEY, message)
  signature = Base64.encode64(hash).chomp
  return AWS_PATH + '?' + req + '&Signature=' + CGI.escape(signature)
end


class AWSRequest
  def initialize
    @params = Hash.new
    @params.store('AWSAccessKeyId', AWS_ACCESS_KEY_ID)
    @params.store('Version', '2009-01-06')
    @params.store("Timestamp", "#{Time.now.getgm.strftime('%Y-%m-%dT%H%%3A%M%%3A%SZ')}")
  end

  def add_param(key, value)
    @params.store(key, value)
  end

  def request_uri
    uri = AWS_PATH + "?"
    message = ''
    (@params.sort_by { |x| x[0].downcase }).each do |e|
      #uri << "#{CGI.escape(e[0])}=#{CGI.escape(e[1])}&"
      #message << "#{CGI.escape(e[0])}=#{CGI.escape(e[1])}&"
      uri << "#{e[0]}=#{e[1]}&"
      message << "#{e[0]}=#{e[1]}&"
    end
    message = ["GET", AWS_URL, AWS_PATH, message.chop].join("\n")

#     message = ['GET',
#                'ecs.amazonaws.jp',
#                '/onca/xml',
#                'AWSAccessKeyId=XXXXXXXXXXX&ContentType=text%2Fxml&IdType=ISBN&ItemId=9780000000000&Operation=ItemLookup&ResponseGroup=ItemAttributes&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2009-05-20T09%3A45%3A14Z&Version=2008-08-19'
#               ].join('\n')

    hmac = OpenSSL::HMAC.new(AWS_SECRET_KEY, OpenSSL::Digest::SHA1.new)
    hmac.update(message)
    signature = CGI.escape(Base64.encode64(hmac.digest).chomp)
    #signature = Base64.encode64(hmac.digest).chomp

#     $stderr.puts "sig'#{signature}'"
#     exit

    uri << "Signature=#{signature}"
  end
end
